//
//  ColCache.swift
//
//  Created by Ink on 2024/7/8.
//  Copyright © 2024 ZM. All rights reserved.
//

import UIKit
import Moya
import Cache

extension String {
    static let netCacheName = "netCacheName"
}

enum CacheKeyType {
    case url
    case urlWithParameters
    case urlLastPathComponent
    case custom(key:String)
}

public class CacheManager {
    
    public static func storage<T: Codable>(ofType type: T.Type) throws -> Storage<String,T>  {
        return try Storage<String,T>(diskConfig: DiskConfig(name: .netCacheName), memoryConfig: MemoryConfig(), transformer: TransformerFactory.forCodable(ofType: type))
    }
    
    // MARK: - 读取
    public static func object<T: Codable>(ofType type: T.Type, forKey key: String) -> T? {
        do {
            let storage = try storage(ofType: type)
            try storage.removeExpiredObjects()
            return (try storage.entry(forKey: key).object)
        } catch {
            print("error\(error)")
            return nil
        }
    }
    
    // MARK: - 缓存
    public static func setObject<T: Codable>(_ object: T?, forKey key: String) {
        do {
            let storage = try storage(ofType: T.self)
            if let object = object {
                try storage.setObject(object, forKey: key)
            }
            else {
                try storage.removeObject(forKey: key)
            }
        } catch  {
            print("error\(error)")
        }
    }
}

extension Task {
    public var parameters: String {
        switch self {
        case .requestParameters(let parameters, _):
            return "\(parameters)"
        case .requestCompositeData(_, let urlParameters):
            return "\(urlParameters)"
        case let .requestCompositeParameters(bodyParameters, _, urlParameters):
            return "\(bodyParameters)\(urlParameters)"
        default:
            return ""
        }
    }
}

extension TargetType {
    public var cachedKey: String {
        return "\(URL(target: self).absoluteString)?\(task.parameters)"
     }
}


